package hhtc.jsjds.controller;

import com.github.pagehelper.PageInfo;
import hhtc.jsjds.constant.RedisKey;
import hhtc.jsjds.entity.Team;
import hhtc.jsjds.entity.Works;
import hhtc.jsjds.enums.StatusCodeEnum;
import hhtc.jsjds.exception.XscoderException;
import hhtc.jsjds.redis.RedisProvider;
import hhtc.jsjds.service.CompetitionService;
import hhtc.jsjds.service.WorksService;
import hhtc.jsjds.utils.CodeUtils;
import hhtc.jsjds.utils.JwtCommonUtils;
import hhtc.jsjds.vo.Result;
import hhtc.jsjds.vo.WorksVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/competition")
public class CompetitionController {


    @Autowired
    CompetitionService competitionService;

    @Autowired
    WorksService worksService;

    @Autowired
    private RedisProvider redisProvider;

    private String upload_starttime;

    private String upload_endtime;

    @GetMapping("/category")
    public Result getAllCategories() {
        return new Result(true, StatusCodeEnum.OK, competitionService.getAllCategories());
    }

    @PostMapping("/team")
    public Result CreateTeam(HttpServletRequest request, String category1, String category2) {
        String uid = JwtCommonUtils.getIDFromToken(request);
        if(StringUtils.isBlank(category1)||StringUtils.isBlank(category2)){
            throw new XscoderException(StatusCodeEnum.BAD_REQUEST);
        }
        Team team = new Team();
        team.setCategoryA_id(category1);
        team.setCategoryB_id(category2);
        team.setUid(uid);
        team.setInvitation_code(CodeUtils.generateCode(8));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
        team.setCreatetime(sdf.format(new Date()));
        competitionService.insertNewTeam(team);
        return new Result(true, StatusCodeEnum.OK);
    }

    @GetMapping("/ownteam")
    public Result GetUserOwnTeams(HttpServletRequest request){
        String uid = JwtCommonUtils.getIDFromToken(request);
        return new Result(true, StatusCodeEnum.OK,competitionService.GetUserOwnTeams(uid));
    }

    @GetMapping("/otherteam")
    public Result GetUserOtherTeams(HttpServletRequest request){
        String uid = JwtCommonUtils.getIDFromToken(request);
        return new Result(true, StatusCodeEnum.OK,competitionService.GetUserOtherTeams(uid));
    }

    @PostMapping("/addteam")
    public Result StudentAddTeam(HttpServletRequest request,String invitation_code){
        if(StringUtils.isBlank(invitation_code)){
            throw new XscoderException(StatusCodeEnum.BAD_REQUEST);
        }
        String uid = JwtCommonUtils.getIDFromToken(request);
        boolean flag = competitionService.StudentAddTeam(uid,invitation_code);
        return new Result(true, StatusCodeEnum.OK);
    }
    @DeleteMapping("/team")
    public Result deleteTeam(HttpServletRequest request,String tid){
        if(StringUtils.isBlank(tid)){
            throw new XscoderException(StatusCodeEnum.BAD_REQUEST);
        }
        String uid = JwtCommonUtils.getIDFromToken(request);
        boolean flag = competitionService.deleteTeam(uid,tid);
        return new Result(true, StatusCodeEnum.OK);
    }

    @GetMapping("/teammate")
    public Result getTeamMate(HttpServletRequest request,String tid){
        if(StringUtils.isBlank(tid)){
            throw new XscoderException(StatusCodeEnum.BAD_REQUEST);
        }
        String uid = JwtCommonUtils.getIDFromToken(request);
        return new Result(true, StatusCodeEnum.OK,competitionService.getTeamMate(uid,tid));
    }

    @PutMapping("/teammate")
    public Result changeTeamMateIndex(HttpServletRequest request,String tid){
        if(StringUtils.isBlank(tid)){
            throw new XscoderException(StatusCodeEnum.BAD_REQUEST);
        }
        String uid = JwtCommonUtils.getIDFromToken(request);
        return new Result(true, StatusCodeEnum.OK,competitionService.changeTeamMateIndex(uid,tid));
    }


    @DeleteMapping("/exitteam")
    public Result userExitTeam(HttpServletRequest request,String tid){
        if(StringUtils.isBlank(tid)){
            throw new XscoderException(StatusCodeEnum.BAD_REQUEST);
        }
        String uid = JwtCommonUtils.getIDFromToken(request);
        boolean flag = competitionService.userExitTeam(uid,tid);
        return new Result(true, StatusCodeEnum.OK);
    }


    @PostMapping("/works")
    public Result getPrivince(HttpServletRequest request, Works works, @RequestBody WorksVO worksVO) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            upload_starttime = redisProvider.get(RedisKey.UPLOAD_START_TIME);
            upload_endtime = redisProvider.get(RedisKey.UPLOAD_END_TIME);
            Date starttime = sdf.parse(upload_starttime);
            Date endtime = sdf.parse(upload_endtime);
            Date now = new Date();
            if (endtime.before(now)) {
                throw new XscoderException(StatusCodeEnum.UPLOAD_HAS_ENDED);
            } else if (starttime.after(now)) {
                throw new XscoderException(StatusCodeEnum.UPLOAD_HAS_NOT_START);
            }
        } catch (Exception e) {
            throw new XscoderException(StatusCodeEnum.PARSE_TIME_FAILED);
        }
        BeanUtils.copyProperties(worksVO, works);
        works.setWorks_img_url(worksVO.getImagestring());
        works.setState("1");
        String uid = JwtCommonUtils.getIDFromToken(request);
        Team team = worksService.getTeamIndex(works.getTeam_id(), uid);
        Works oldwork = worksService.getWorksByTeam_id(works.getTeam_id());
        if (team != null && oldwork == null) {
            works.setCategory_id(team.getCategoryB_id());

            try {
                works.setWorks_update_time(sdf.format(new Date()));
                works.setWorks_create_time(sdf.format(new Date()));
            } catch (Exception e) {
                throw new XscoderException(StatusCodeEnum.PARSE_TIME_FAILED);
            }
            if (worksService.setWorks(works) != 0) {
                return new Result(true, StatusCodeEnum.OK);
            } else {
                throw new XscoderException(StatusCodeEnum.OPT_FAILD);
            }
        } else if (team != null) {
            try {
                works.setWorks_update_time(sdf.format(new Date()));
            } catch (Exception e) {
                throw new XscoderException(StatusCodeEnum.PARSE_TIME_FAILED);
            }
            if (worksService.updateWorks(works)) {
                return new Result(true, StatusCodeEnum.OK);
            } else {
                throw new XscoderException(StatusCodeEnum.OPT_FAILD);
            }
        }else {
            throw new XscoderException(StatusCodeEnum.OPT_NOT_ALLOWED);
        }
    }

    @GetMapping("/works")
    public Result getWorksByTid(HttpServletRequest request,String tid){
        String uid = JwtCommonUtils.getIDFromToken(request);
        Team team = worksService.getTeamIndex(tid,uid );
        if(team==null){
            throw new XscoderException(StatusCodeEnum.OPT_NOT_ALLOWED);
        }else{
            return new Result(true, StatusCodeEnum.OK,worksService.getWorksByTeam_id(tid));
        }
    }

    @GetMapping("/tasks10")
    public List<Works> getTasks10(HttpServletRequest request){
        String uid = JwtCommonUtils.getIDFromToken(request);
        return worksService.getTasks10(uid);
    }

    @GetMapping("/completed")
    public List<Works> getAllCompletedWorks(HttpServletRequest request){
        String uid = JwtCommonUtils.getIDFromToken(request);
        return worksService.getAllCompletedWorks(uid);
    }

    @PostMapping("/eliminate")
    public boolean setTeamEliminatedByWid(HttpServletRequest request,@RequestParam String wid){
        return competitionService.setTeamEliminatedByWid(wid);
    }

    @PostMapping("/passed")
    public boolean setTeamPassedByWid(HttpServletRequest request,@RequestParam String wid){
        return competitionService.setTeamPassedByWid(wid);
    }

    @GetMapping("/sysadminworks")
    public  PageInfo<Works> sysAdminGetAllWorks(HttpServletRequest request,@RequestParam Integer page,@RequestParam Integer pageSize){
        return competitionService.sysAdminGetAllWorks(page,pageSize);
    }

    @PostMapping("/workspassed")
    public boolean setWorksPassed(HttpServletRequest request,@RequestParam String wid){
        return competitionService.setTeamPassedByWid(wid);
    }


    @GetMapping("/finalworks")
    public  Works getWorksByTeamId(HttpServletRequest request,@RequestParam Integer team_id){
        String uid = JwtCommonUtils.getIDFromToken(request);
        return competitionService.getWorksByTeamId(uid,team_id);
    }

    @GetMapping("/finalcompleted")
    public List<Works> getFinalAllCompletedWorks(HttpServletRequest request){
        String uid = JwtCommonUtils.getIDFromToken(request);
        return worksService.getFinalAllCompletedWorks(uid);
    }

    @GetMapping("/sysfinalcompleted")
    public List<Works> getSYSAllCompletedWorks(HttpServletRequest request,String team_id){
        return worksService.getSYSAllCompletedWorks(team_id);
    }


//    @PostMapping("/seq")
//    public boolean seq(HttpServletRequest request,@RequestParam String wid){
////        competitionService.randomSort();
//        return competitionService.setTeamPassedByWid(wid);
//    }


}
